<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\Route;

class Permission extends Model
{
    protected $fillable = [
        'id', 'menu_id', 'name', 'action',
    ];

    protected $hidden = [

    ];

    public function generateAllPermission()
    {
//        $app = app();
        $routes = Route::getRoutes()->getRoutes();
        $actions = [];
        foreach ( $routes as $k => $value ) {
            $action = $value->getAction();
            if ( isset($action['controller']) && isset($action['middleware']) && is_array($action['middleware']) ) {
                if ( in_array('auth.permission', $action['middleware'], true) && strstr($action['controller'], 'App\Http\Controllers\Admin\V1') ) {
                    $actions[$value->uri] = $action['controller'];
                }
            }
        }
        if ( empty($actions) )
            return $actions;
        $has = self::query()->whereIn('action', $actions)->get()->toArray();
        $has = array_column($has, null, 'action');

        $create = [];
        $menu = Menu::query()->where('name', '临时菜单')->first();
        foreach ( $actions as $k => $v ) {
            if ( !isset($has[$v]) ) {
                if ( empty($menu) ) {
                    $menu = Menu::query()->create(['pid' => 0, 'name' => '临时菜单', 'route' => '', 'sort' => 9999, 'display' => 0]);
                }
                $create[] = [
                    'menu_id' => $menu->id,
                    'name' => $k,
                    'action' => $v,
                    'created_at' => Carbon::now()->toDateTimeString(),
                    'updated_at' => Carbon::now()->toDateTimeString(),
                ];
            }
        }

        if ( !empty($create) ) {
            self::query()->insert($create);
        }
        return $create;
    }

}
